from rest_framework import viewsets, mixins, serializers
from cron.models import CronJob,DjangoCronjob
from django_filters import rest_framework as filters
from datetime import datetime


class CronJobSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    class Meta:
        model = CronJob
        fields = '__all__'
        read_only_fields = ("id",)

#DjangoJob自身任务模型
from django_apscheduler.models import DjangoJob
class DjangoJobSerializer(serializers.ModelSerializer):
    next_run_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    class Meta:
        model = DjangoJob
        fields = '__all__'
        read_only_fields = ("id",)


class DjangoCronjobSerializer(serializers.ModelSerializer):
    job = DjangoJobSerializer(read_only=True,required=False)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    # next_run_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    # job = serializers.PrimaryKeyRelatedField(
    #     queryset=DjangoJob.objects.all(),#这指定了当反序列化（即从请求数据创建或更新模型实例）时，哪些DjangoJob实例是可以被接受的。在这个例子中，它允许所有DjangoJob实例。
    #     required=False,  # 允许job字段为空（在序列化器验证时）
    #     #allow_null=True  # 如果DjangoJob模型允许null值的话（但通常OneToOneField不允许null）
    # )
    class Meta:
        model = DjangoCronjob
        fields = '__all__'
        read_only_fields = ("id",)

# 定义过滤器,过滤任务名字
class DjangoCronjobFilter(filters.FilterSet):
    job = filters.CharFilter(field_name="job__id")
    class Meta:
        model = DjangoCronjob
        fields = ("job",)

#DjangoJob自身任务执行记录
from django_apscheduler.models import DjangoJobExecution
class DjangoJobExecutionSerializer(serializers.ModelSerializer):
    job = DjangoJobSerializer(read_only=True, required=False)
    run_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    finished = serializers.SerializerMethodField()  #用SerializerMethodFiled二次处理，转换为时间格式
    class Meta:
        model = DjangoJobExecution
        fields = '__all__'
        read_only_fields = ("id",)

    #重写finished字段显示方式
    def get_finished(self, obj):
        # obj 是模型实例，但在这种情况下，我们可能只是从某个地方获取'finished'字符串
        # 假设我们已经有了一个名为'finished'的字符串属性或方法返回值
        timestamp_str = getattr(obj, 'finished', None)  # 或者从其他地方获取时间戳字符串

        if timestamp_str is not None:
            # 将字符串转换为浮点数（假设它是秒为单位的时间戳）
            timestamp = float(timestamp_str)
            # 将时间戳转换为datetime对象
            dt_object = datetime.fromtimestamp(timestamp)
            # 格式化datetime对象为字符串
            return dt_object.strftime('%Y-%m-%d %H:%M:%S')


# 定义过滤器,过滤任务名字
class DjangoJobExecutionFilter(filters.FilterSet):
    job = filters.CharFilter(field_name="job__id")
    status = filters.CharFilter(field_name="status")
    class Meta:
        model = DjangoJobExecution
        fields = ("job",)